package com.yimixian.app.user;

import android.content.Intent;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;
import com.yimixian.app.R;
import com.yimixian.app.SystemFramework;
import com.yimixian.app.common.StatConstants;
import com.yimixian.app.common.YmxTitleBarActivity;
import com.yimixian.app.net.HttpApi;
import com.yimixian.app.rest.YmxDataService;
import com.yimixian.app.util.UiUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

public class BindMobileActivity extends YmxTitleBarActivity {

    private static final String VERIFY_CODE_REGEX = "^\\d{6}$";
    private static final String PHONE_NUMBER_REGEX = "^1\\d{10}$";
    private EditText phone_number_edit_text, verify_code_edit_text;
    private TextView get_verify_code_button, submit_verify_code_button;
    private CountDownTimer mCountDownTimer;
    private YmxDataService mYmxDataService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind_mobile);

        get_verify_code_button = (TextView) findViewById(R.id.get_verify_code_button);
        submit_verify_code_button = (TextView) findViewById(R.id.submit_verify_code_button);
        phone_number_edit_text = (EditText) findViewById(R.id.phone_number_edit_text);
        verify_code_edit_text = (EditText) findViewById(R.id.verify_code_edit_text);

        mYmxDataService = YmxDataService.getInstance();
        verify_code_edit_text.addTextChangedListener(new UserTextWatcher(
                new Runnable() {
                    @Override
                    public void run() {
                        onVerifyCodeChanged();
                    }
                }));
        phone_number_edit_text.addTextChangedListener(new UserTextWatcher(
                new Runnable() {
                    @Override
                    public void run() {
                        onPhoneNumberChanged();
                    }
                }));

        get_verify_code_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MobclickAgent.onEvent(BindMobileActivity.this, StatConstants.LOGIN_GET_SMS_CODE);
                get_verify_code_button.setEnabled(false);
                mYmxDataService.getVerifyCode(getPhoneNumber())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(
                                new Action1<Boolean>() {
                                    @Override
                                    public void call(Boolean aBoolean) {
                                        startCountDown();
                                    }
                                },
                                new Action1<Throwable>() {
                                    @Override
                                    public void call(Throwable throwable) {
                                        UiUtils.toastError(
                                                SystemFramework.getInstance().getGlobalContext(), throwable);
//                                        get_verify_code_button.setEnabled(true);
                                        startCountDown();
                                    }
                                });
                verify_code_edit_text.requestFocus();
            }
        });

        submit_verify_code_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!checkedInputData()){
                    return;
                }
                MobclickAgent.onEvent(BindMobileActivity.this, StatConstants.LOGIN_SEND_SMS_CODE);
                setCommitBackground(false);

                Map<String, String> map = new HashMap<String, String>();
                map.put("tel", getPhoneNumber());
                map.put("verify_code", getVerifyCode());
                map.put("uuid", getIntent().getStringExtra("uuid"));
                HttpApi.startPostRequest("/v3/bind_tel", map, new HttpApi.RequestCallBack() {
                    @Override
                    public void requestSuccess(String result) {

                        setCommitBackground(true);
                        try {
                            JSONObject json = new JSONObject(result);
                            if(json.has("error")){
                                UiUtils.showToast(json.optJSONObject("error").optString("message"));
                                return;
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        setResult(1000, new Intent().putExtra("data", result));
                        finish();
                        overridePendingTransition(0, 0);

                    }

                    @Override
                    public void requestError() {
                    }

                    @Override
                    public void alwaysDo() {
                    }
                });
            }
        });

        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                overridePendingTransition(0, R.anim.slide_out_right);
            }
        });

    }

    private String getVerifyCode() {
        return verify_code_edit_text.getText() != null ? verify_code_edit_text.getText().toString()
                : "";
    }

    private String getPhoneNumber() {
        return phone_number_edit_text.getText() != null ? phone_number_edit_text.getText().toString()
                : "";
    }

    public boolean checkedInputData(){
        boolean isChecked=false;
        boolean phoneNumberMatched = getPhoneNumber().matches(PHONE_NUMBER_REGEX);
        if (!phoneNumberMatched){
            UiUtils.showToast("请输入正确的手机号");
            return isChecked;
        }
        if (TextUtils.isEmpty(getVerifyCode())){
            UiUtils.showToast("请输入验证码");
            return isChecked;
        }
        if (getVerifyCode().length()<6){
            UiUtils.showToast("验证码长度不足6位");
            return isChecked;
        }
        boolean codeMatched=getVerifyCode().matches(VERIFY_CODE_REGEX);
        if (codeMatched){
            isChecked=true;
        }
        return isChecked;
    }

    public void setCommitBackground(boolean isClickable){
        if (isClickable) {
            submit_verify_code_button.setBackgroundDrawable(getResources().getDrawable(R.drawable.orange_button_normal_bg));
        }
        else {
            submit_verify_code_button.setBackgroundDrawable(getResources().getDrawable(R.drawable.rounded_button_disabled));
        }
    }

    private void onVerifyCodeChanged() {
        setCommitBackground(getVerifyCode().matches(VERIFY_CODE_REGEX));
    }

    private void onPhoneNumberChanged() {
        boolean phoneNumberMatched = getPhoneNumber().matches(PHONE_NUMBER_REGEX);
        get_verify_code_button.setEnabled(mCountDownTimer == null && phoneNumberMatched);
        setCommitBackground(getVerifyCode().matches(VERIFY_CODE_REGEX)
                && phoneNumberMatched);
    }

    private void startCountDown() {
        mCountDownTimer = new CountDownTimer(120 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                get_verify_code_button.setText((millisUntilFinished / 1000) + "秒后重试");
            }

            @Override
            public void onFinish() {
                get_verify_code_button.setEnabled(true);
                get_verify_code_button.setText("获取验证码");
                mCountDownTimer = null;
            }
        };
        mCountDownTimer.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
            mCountDownTimer = null;
        }
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(0, R.anim.slide_out_right);
    }

    @Override
    protected String getTitleBarText() {
        return "绑定手机号";
    }
}
